package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.exception.BusinessException;
import com.yt.sys.models.bo.SysUserRoleReplaceBO;
import com.yt.sys.models.bo.SysUserRoleSaveBO;
import com.yt.sys.models.vo.SysUserRoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.bo.SysUserRoleBO;
import com.yt.sys.models.dto.SysUserRoleDTO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色信息控制器
 *
 * @author chen
 * @Date 2025-09-05 18:51:40
 */

@RestController
@RequestMapping("/api/sysUserRole")
@Slf4j
@Api(value = "SysUserRoleApiController", tags = "用户角色关联API接口")
public class SysUserRoleApiController {

    @DubboReference
    private ISysUserRoleService sysUserRoleService;

    @ApiOperation(value = "新增用户角色关联", notes = "客户端新增用户与角色的关联关系")
    @PostMapping("/add")
    public Result<SysUserRoleVO> add(@RequestBody SysUserRoleSaveBO saveBO) {
        try {
            boolean success = sysUserRoleService.add(saveBO);
            if (success) {
                // 查询新增的关联信息
                List<SysUserRoleVO> list = sysUserRoleService.selectByUserId(saveBO.getUserId()).stream()
                        .filter(dto -> dto.getRoleId().equals(saveBO.getRoleId()))
                        .map(dto -> {
                            SysUserRoleVO vo = new SysUserRoleVO();
                            org.springframework.beans.BeanUtils.copyProperties(dto, vo);
                            return vo;
                        }).collect(Collectors.toList());
                return list.isEmpty() ? new Result<>(CodeEnum.FAIL_100010) : new Result<>(list.get(0));
            }
            return new Result<>(CodeEnum.FAIL_100007);
        } catch (Exception e) {
            log.error("新增用户角色关联失败", e);
            return new Result<>(CodeEnum.FAIL_100007.getCode(), e.getMessage());
        }
    }

    @GetMapping("/user/{userId}/roles")
    public Result<List<SysUserRoleVO>> getUserRoles(@PathVariable Long userId) {
        if (userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        // 直接获取VO列表
        List<SysUserRoleVO> voList = sysUserRoleService.selectByUserId(userId);
        return new Result<>(voList);
    }

    // 查询角色关联的用户
    @GetMapping("/role/{roleId}/users")
    public Result<List<SysUserRoleVO>> getRoleUsers(@PathVariable Long roleId) {
        if (roleId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        // 直接获取VO列表
        List<SysUserRoleVO> voList = sysUserRoleService.selectByRoleId(roleId);
        return new Result<>(voList);
    }

    // 分页查询
    @ApiOperation(value = "分页查询关联列表", notes = "客户端分页查询用户角色关联关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNo", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<SysUserRoleVO>> list(
            Long userId,
            Long roleId,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        SysUserRoleBO bo = new SysUserRoleBO();
        bo.setUserId(userId);
        bo.setRoleId(roleId);
        bo.setPageNo(pageNo);
        bo.setPageSize(pageSize);

        Page<SysUserRoleVO> page = new Page<>(pageNo, pageSize);
        page = sysUserRoleService.selectUserRolePage(page, bo);  // 直接获取联表查询结果
        return new Result<>(page);
    }


    @ApiOperation(value = "删除用户角色关联", notes = "根据用户ID删除该用户的角色关联关系")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "path", dataType = "Long")
    @DeleteMapping("/delete/{userId}")
    public Result<Void> deleteByUserId(@PathVariable Long userId) {
        if (userId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        Wrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);

        boolean success = sysUserRoleService.delete(wrapper);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    @ApiOperation(value = "更换用户绑定的唯一角色", notes = "每个用户只能绑定一个角色，操作后会覆盖原有角色")
    @ApiImplicitParam(name = "replace", value = "更换角色参数（用户ID+唯一角色ID）", required = true, dataType = "SysUserRoleReplaceBO")
    @PostMapping("/replaceRole")
    public Result<Void> replaceUniqueRole(@RequestBody SysUserRoleReplaceBO replaceBO) {
        try {
            // 参数校验
            if (replaceBO.getUserId() == null) {
                return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID不能为空");
            }
            if (replaceBO.getRoleId() == null) {
                return new Result<>(CodeEnum.FAIL_100002.getCode(), "角色ID不能为空");
            }

            // 调用服务层更换角色
            boolean success = sysUserRoleService.replaceUniqueRole(replaceBO);
            return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100007);
        } catch (BusinessException e) {
            log.error("更换用户唯一角色失败：{}", e.getMessage());
            return new Result<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("更换用户唯一角色发生异常", e);
            return new Result<>(CodeEnum.FAIL_100007.getCode(), "更换角色失败");
        }
    }
}
